const express = require("express");
const router = express.Router();
const User = require("../db/model/userModel");
const Mail = require("../utils/mail");
const { setToken, getTokenInfo } = require("../utils/token");
const { getCounter } = require("../utils/counter");


/**
 * @api {post} /user/reg 用户注册
 * @apiName 用户注册
 * @apiGroup User
 *
 * @apiParam {String} us 用户名（邮箱）
 * @apiParam {String} ps 用户密码
 * @apiParam {String} openid 小程序openid
 * @apiParam {code} ps 验证码
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "msg": "创建成功"
 *     }
 */
// 小程序和pc web的注册，通过 us 用户名进行关联，如果用户名一样，则说明是同一用户，此用户同时保存 ps 和 openid
router.post("/reg", (req, res) => {
  let { us, ps, openid } = req.body;

  if (!us || (!ps && !openid) ) return res.send({ code: 500, msg: "缺少参数" });
  User.find({ us })
    .then((data) => {
      const time = new Date().getTime();
      if (data.length === 0) {
         User.insertMany({ us, ps, openid, time });
        res.send({ code: 200, msg: "创建成功" });
        return
      } else {
        const existUser = data[0]
        // 如果原来pc端已经注册，如果请求有 openid 说明是小程序注册
        if(openid && !existUser.openid){
          User.updateOne({ us }, { us, ps: existUser.ps, openid, time })
          .then((e) => {
            if(e.nModified === 1){
              res.send({ code: 200, msg: "创建成功" });
              return
            }
            res.send({ code: 500, msg: '更新用户失败' })
           
          })
          .catch((e) => {
            console.log(e)
            res.send({ code: 500, msg: '更新用户失败' })
          })
          return
        }
        // 如果原来已经小程序注册过，pc端再注册
        if(ps && !existUser.ps){
          User.updateOne({ us }, { us, ps, openid: existUser.openid, time })
          .then((e) => {
            if(e.nModified === 1){
              res.send({ code: 200, msg: "创建成功" });
              return
            }
            res.send({ code: 500, msg: '更新用户失败' })
           
          })
          .catch((e) => {
            console.log(e)
            res.send({ code: 500, msg: '更新用户失败' })
          })
          return
        }

        
        res.send({ code: 500, msg: "用户名已存在" });
      }
    }).catch((err) => {
      if(!err) return
      console.log(err)
      res.send({ code: 500, msg: "创建失败" });
    });
});




/**
 * @api {post} /user/login 用户登录
 * @apiName 用户登录
 * @apiGroup User
 *
 * @apiParam {String} us 用户名（邮箱）
 * @apiParam {String} ps 用户密码
 * @apiParam {String} openid 小程序openid
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "msg": "登录成功"
 *     }
 */
router.post("/login", (req, res) => {
  let { us, ps, openid } = req.body;
  if (!us || (!ps && !openid)) return res.send({ code: 500, msg: "缺少参数" });

  User.find({ us })
    .then((datas) => {
      if(datas && !datas.length) res.send({ code: 500, msg: "账号或密码不正确" });
      const data = datas.find(item=> item.ps === ps || item.openid === openid)
      if (data) {
        // if (!data.state) return res.send({ code: 502, msg: "账号已被禁用" });
        let token = setToken({ login: true, name: us, roleId: data.roleId });
        res.send({ code: 200, msg: "登录成功", token });
      } else {
        res.send({ code: 500, msg: "账号或密码不正确" });
      }
    })
    .catch(() => {
      res.send({ code: 500, msg: "登录失败" });
    });
});


/**
 * @api {post} /user/getInfo 获取用户详情
 * @apiName 获取用户详情
 * @apiGroup User
 *
 * @apiParam {String} openid 用户名（邮箱）
 * @apiParam {String} us 用户名
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "code": "200",
 *       "msg": "登录成功"
 *     }
 */
router.get("/getInfo", (req, res) => {
  let us = req.query.us;
  let openid = req.query.openid;
  if (!(us||openid) ) return res.send({ code: 500, msg: "缺少参数" });
  const query = {}
  if(openid) query.openid = openid;
  if(us) query.us = openid;

  User.find(query)
    .then((data) => {
      if (data && data.length) {
        const {ps, openid, ...rest} = data[0];
        res.send({ code: 200, msg: "获取用户信息成功", data: rest });
      } else {
        res.send({ code: 500, msg: "没有该用户" });
      }
    })
    .catch(() => {
      res.send({ code: 500, msg: "登录失败" });
    });
});



/**
 * @api {post} /user/updateps 用户修改密码
 * @apiName 用户修改密码
 * @apiGroup User
 *
 * @apiParam {String} oldPs 旧密码
 * @apiParam {String} newPs 新密码
 */
router.post("/updateps", (req, res) => {
  let { oldPs, newPs } = req.body;
  if (!oldPs || !newPs) return res.send({ code: 500, msg: "缺少参数" });
  getTokenInfo(req.headers.token)
    .then((data) => {
      return User.updateOne({ us: data.data.name }, { ps: newPs });
    })
    .then(() => {
      res.send({ code: 200, msg: "修改成功" });
    })
    .catch(() => {
      res.send({ code: 500, msg: "修改失败" });
    });
});


/**
 * @api {post} /user/del 用户删除
 * @apiName 用户删除
 * @apiGroup User
 *
 * @apiParam {Number} _id id
 */
router.post("/del", (req, res) => {
  const { _id } = req.body;

  User.remove({ _id })
    .then((data) => {
      res.send({ code: 200, msg: "删除成功" });
    })
    .catch(() => {
      res.send({ code: 500, msg: "删除失败" });
    });
});


/**
 * @api {post} /user/page 用户列表
 * @apiName 用户列表
 * @apiGroup User
 *
 * @apiParam {Number} pageNo 页数
 * @apiParam {Number} pageSize 条数
 * @apiParam {Number} key 关键字查询
 */
router.post("/page", (req, res) => {
  const pageNo = Number(req.body.pageNo) || 1;
  const pageSize = Number(req.body.pageSize) || 10;

  const { key } = req.body;
  const reg = new RegExp(key);
  let query = { $or: [{ us: { $regex: reg } }] };
  User.countDocuments(query, (err, count) => {
    if (err) {
      res.send({ code: 500, msg: "用户列表获取失败" });
      return;
    }

    User.aggregate(
      [
        {
          $match: query,
        },
        {
          $lookup: {
            // 多表联查  通过roleId获取roles表数据
            from: "roles", // 需要关联的表roles
            localField: "roleId", // users表需要关联的键
            foreignField: "roleId", // roles表需要关联的键
            as: "roles", // 对应的外键集合的数据，是个数组 例如： "roles": [{ "roleName": "超级管理员"}]
          },
        },
        {
          $skip: pageSize * (pageNo - 1),
        },
        {
          $limit: pageSize,
        },
        {
          // $project中的字段值 为1表示筛选该字段，为0表示过滤该字段
          $project: {
            ps: 0,
            roles: { _id: 0, roleDesc: 0, __v: 0, authIds: 0, roleId: 0 },
          },
        },
      ],
      function (err, docs) {
        if (err) {
          res.send({ code: 500, msg: "用户列表获取失败" });
          return;
        }
        res.send({
          code: 200,
          data: docs,
          total: count,
          pageNo: pageNo,
          pageSize: pageSize,
          msg: "用户列表获取成功",
        });
      }
    );
  });
});


module.exports = router;
